package com.zj.typeFilter;

import com.zj.annotations.District;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.type.filter.AbstractTypeHierarchyTraversingFilter;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ClassUtils;
import org.springframework.util.PathMatcher;


import java.util.Properties;

public class MyTypeFilter extends AbstractTypeHierarchyTraversingFilter {

    private static String districtName;
    private static PathMatcher pathMatcher = new AntPathMatcher();

    static {
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties("district.properties");
            districtName = properties.getProperty("common.district");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public MyTypeFilter() {
        super(false, false);
    }

    protected boolean matchClassName(String className) {
        if (isRelativeClass(className)) {
            return false;
        }
        Class<?> aClass = null;
        District annotation = null;
        try {
            aClass = Class.forName(className);
            annotation = aClass.getAnnotation(District.class);
            if (annotation == null) {
                return false;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return !districtName.equalsIgnoreCase(annotation.value());
    }

    private String PATH_PATTERN = ClassUtils.convertClassNameToResourcePath("com.zj.*.*");

    private boolean isRelativeClass(String name) {
        String path = ClassUtils.convertClassNameToResourcePath(name);
        return pathMatcher.match(PATH_PATTERN, path);
    }


}
